package xin.cymall.api;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xin.cymall.common.api.annotation.IgnoreAuth;
import xin.cymall.common.exception.MyException;
import xin.cymall.common.redis.RedisCache;
import xin.cymall.common.utils.R;
import xin.cymall.common.utils.StringUtil;
import xin.cymall.entity.User;
import xin.cymall.service.TokenService;
import xin.cymall.service.UserService;

import java.util.Map;

/**
 * API登录授权
 *
 * @author chenyi
 * @email 228112142@qq.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     */
    @IgnoreAuth
    @PostMapping("login")
    @ApiOperation(value="login", notes="登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true,dataType = "string",paramType = "query"),
    })
    //获取redis缓存
    @RedisCache(type=User.class)
    public R login(String username,String password){
        if(StringUtil.isEmpty(username)){
            throw  new MyException("用户名不能为空");
        }
        if(StringUtil.isEmpty(password)){
            throw  new MyException("密码不能为空");
        }
        //用户登录
        String userId = userService.login(username, password);

        //生成token
        Map<String, Object> map = tokenService.createToken(userId);

        return R.ok(map);
    }

}
